package org.anyin.gitee.shiro.config;

import org.anyin.gitee.shiro.shiro.TokenCredentialsMatcher;
import org.anyin.gitee.shiro.shiro.TokenFilter;
import org.anyin.gitee.shiro.shiro.TokenRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public TokenRealm tokenRealm(){
        TokenRealm realm = new TokenRealm();
        realm.setCredentialsMatcher(credentialsMatcher());
        return realm;
    }

    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        // 认证过滤器
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("token", new TokenFilter());

        // 忽略路径
        Map<String, String>  filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/login", DefaultFilter.anon.name());
        filterChainDefinitionMap.put("/logout", DefaultFilter.anon.name());
        filterChainDefinitionMap.put("/**", "token");

        // 装配bean
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager());
        filterFactoryBean.setFilters(filterMap);
        filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return filterFactoryBean;
    }

    @Bean
    public CredentialsMatcher credentialsMatcher(){
        return new TokenCredentialsMatcher();
    }

    @Bean
    public SessionsSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(tokenRealm());
        return securityManager;
    }
}
